package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.database.IconDBHelper;
import com.example.myapplication.enity.IconInfo;
import com.example.myapplication.util.FileUtil;
import com.example.myapplication.util.SharedUtil;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private IconDBHelper mDBHelper;
    private GridLayout gl_channel;
    private ScrollView scrollView;
    private Button search_button;
    private EditText editText;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        scrollView = findViewById(R.id.scrollView);
        gl_channel = findViewById(R.id.gl_channel);
        search_button = findViewById(R.id.search);
        editText = findViewById(R.id.edittext);

        mDBHelper = IconDBHelper.getInstance(this);
        mDBHelper.openReadLink();
        mDBHelper.openWriteLink();


        try {
            initIconsInfo();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        getIcons();

        search_button.setOnClickListener(v ->{
            Intent intent = new Intent(MainActivity.this, SearchActivity.class);
            intent.putExtra("name", String.valueOf(editText.getText()));
            startActivity(intent);
        });

        // 设置滑动监听
        scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                int scrollY = scrollView.getScrollY();
                int screenHeight = scrollView.getHeight();

                for (int i = 0; i < gl_channel.getChildCount(); i++) {
                    View child = gl_channel.getChildAt(i);
                    if (child instanceof LinearLayout) {
                        int childTop = child.getTop();
                        int childBottom = child.getBottom();

                        // 判断是否在可视范围内
                        if (childTop < scrollY + screenHeight && childBottom > scrollY) {
                            // 在可视范围内，加载图片
                            ImageView img = child.findViewById(R.id.img);
                            TextView name = child.findViewById(R.id.name);
                            img.setImageURI(Uri.parse((String) img.getTag()));
                            name.setText((String) name.getTag());
                        }
                        else{
                            ImageView img = child.findViewById(R.id.img);
                            img.setImageURI(null);
                        }
                    }
                }
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDBHelper.closeLink();

    }

    private void getIcons() {
        // 查询数据库中的所有icon记录
        List<IconInfo> list = mDBHelper.queryAllIconsInfo();
        Log.i("1", String.valueOf(list.size()));
        // 移除下面的所有子视图
        gl_channel.removeAllViews();
        int i = 0;
        for (IconInfo info : list) {
            // 获取布局文件item_icon.xml的根视图
            View view = LayoutInflater.from(this).inflate(R.layout.item_icon, null);

            ImageView img = view.findViewById(R.id.img);
            TextView name = view.findViewById(R.id.name);

            if(i <= 8){
                img.setImageURI(Uri.parse(info.path));
                name.setText(info.name);
                i ++;
            }
            // 给控件设置值
            img.setTag(info.path);
            name.setTag(info.name);

            // 把图标视图添加到网格布局
            gl_channel.addView(view);
        }
    }

    // 首次启动初始化图片和数据库
    private void initIconsInfo() throws IllegalAccessException {
        boolean isFirst = SharedUtil.getInstance(this).readBoolean("first", true);
        String directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + File.separatorChar;

        if (isFirst) {
            List<IconInfo> list = IconInfo.getDefaultList(this);
            for (IconInfo info : list) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), info.pic);
                String path = directory + info.name + ".png";
                // 往存储卡保存图片
                FileUtil.saveImage(path, bitmap);
                // 回收位图对象
                bitmap.recycle();
                info.path = path;
            }
            // 打开数据库，把信息插入到表中
            IconDBHelper dbHelper = IconDBHelper.getInstance(this);
            dbHelper.openWriteLink();
            dbHelper.insertIconsInfos(list);
            dbHelper.closeLink();
            // 把是否首次打开写入共享参数
            SharedUtil.getInstance(this).writeBoolean("first", false);
        }
    }


}